//
//  YMPhotosViewController.swift
//  YMPhotosDemo
//
//  Created by youmy on 2019/12/17.
//  Copyright © 2019 youmy. All rights reserved.
//

import UIKit
import Photos

private let kCellId = "CellId"

private let MaxCount = 6

class YMPhotosViewController: UIViewController {
    
    @IBOutlet weak var nearbyBtn: UIButton!
    
    ///取得的资源结果，用了存放的PHAsset
    var assetsFetchResults:PHFetchResult<PHAsset>?
     
    ///缩略图大小
    var assetGridThumbnailSize:CGSize!
     
    /// 带缓存的图片管理对象
    var imageManager:PHCachingImageManager!
    
    /// 选择的图片最多6张
    var selecteImageDic = [Int: PHAsset]()
    
    var cells = [Int: Bool]()
    
    var layout = UICollectionViewFlowLayout()
    
    fileprivate lazy var collectionView : UICollectionView = {
        layout.minimumLineSpacing = 5
        layout.minimumInteritemSpacing = 5
        let cellW = (UIScreen.main.bounds.width - 20) / 3
        let cellH = (cellW * 3)/2
        layout.itemSize = CGSize(width: cellW, height: cellH)
        layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        
        let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.showsVerticalScrollIndicator = false
        collectionView.dataSource = self
        collectionView.delegate = self
        
        return collectionView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
         
        //根据单元格的尺寸计算我们需要的缩略图大小
//        let scale = UIScreen.main.scale
        let cellSize = layout.itemSize
//        assetGridThumbnailSize = CGSize(width:cellSize.width*scale ,
//                                        height:cellSize.height*scale)
        assetGridThumbnailSize = cellSize
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        UIView.setAnimationsEnabled(false)
        
        view.addSubview(collectionView)
        
        collectionView.register(UINib(nibName: "YMPhotoCell", bundle: nil), forCellWithReuseIdentifier: kCellId)

        //申请权限
        PHPhotoLibrary.requestAuthorization({[weak self] (status) in
            if status != .authorized {
                return
            }
             
            //则获取所有资源
            let allPhotosOptions = PHFetchOptions()
            //按照创建时间倒序排列
            allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",
                                                                 ascending: false)]
            //只获取图片
            allPhotosOptions.predicate = NSPredicate(format: "mediaType = %d",
                                                     PHAssetMediaType.image.rawValue)
            self?.assetsFetchResults = PHAsset.fetchAssets(with: PHAssetMediaType.image,
                                                     options: allPhotosOptions)
            let count = self?.assetsFetchResults?.count ?? 0
            
            for i in 0..<count {
                self?.cells[i] = false
            }
            
             
            // 初始化和重置缓存
            self?.imageManager = PHCachingImageManager()
            self?.resetCachedAssets()
             
            //collection view 重新加载数据
            DispatchQueue.main.async{
                self?.collectionView.reloadData()
            }
        })
    }
    
    //重置缓存
    func resetCachedAssets(){
        self.imageManager.stopCachingImagesForAllAssets()
    }
    
    @IBAction func seleteAlbumAction(_ sender: UIButton) {
        
        
    }
    
    
    @IBAction func dismissAction(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
    
}

extension YMPhotosViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.assetsFetchResults?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // 获取设计的单元格，不需要再动态添加界面元素
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellId, for: indexPath) as! YMPhotoCell
        
        let flag = cells[indexPath.item] ?? false
        
        cell.selectIV.image = flag == true ? UIImage(named: "selected") : UIImage(named: "select")
        
        if selecteImageDic.count == 6 && flag == false {
            cell.selectIV.isHidden = true
        }else{
            cell.selectIV.isHidden = false
        }
         
        if let asset = self.assetsFetchResults?[indexPath.row] {
            //获取缩略图
            self.imageManager.requestImage(for: asset, targetSize: assetGridThumbnailSize,
                        contentMode: PHImageContentMode.aspectFill,
                        options: nil) { (image, nfo) in
                            if let image = image {
                                cell.imageV.image = image
                                print(image)
                            }
            }
        }
         
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
                
        let flag = cells[indexPath.item]
        
        if let flag = flag, flag == true {
            
            selecteImageDic.removeValue(forKey: indexPath.item)
            cells[indexPath.item] = false
            collectionView.reloadData()
            
        }else{
            if selecteImageDic.keys.count < 6{
                cells[indexPath.item] = true
                if let asset = self.assetsFetchResults?[indexPath.row] {
                    //获取缩略图
                    self.imageManager.requestImage(for: asset, targetSize: assetGridThumbnailSize,
                                contentMode: PHImageContentMode.aspectFill,
                                options: nil) {[weak self] (image, nfo) in
                                    if let image = image {
                                        self?.selecteImageDic[indexPath.item] = asset
                                        print(image)
                                    }
                                    
                                    if self?.selecteImageDic.keys.count == 6 {
                                        UIView.performWithoutAnimation {
                                            collectionView.reloadSections(IndexSet(integer: 0))
                                        }
                                    }else{
                                        collectionView.reloadItems(at: [indexPath])
                                    }
                                    
                    }
                }
            }
        }
    }
    
}
